<template>
  <v-container >
    <v-row justify="center">
      <v-col cols="12" md="12" class="h-[800px] flex justify-center items-center">
        <!-- Loading Skeleton -->
        <v-card v-if="isLoading" elevation="0" rounded="lg" class="px-6 py-4 ">
          <v-row align="center" justify="space-between" class="mb-4">
            <v-col cols="auto">
              <v-skeleton-loader type="text" width="120"></v-skeleton-loader>
            </v-col>
            <v-col cols="auto">
              <v-skeleton-loader type="chip"></v-skeleton-loader>
            </v-col>
          </v-row>

          <v-row>
            <v-col cols="12" >
              <div class="d-flex gap-4">
                <v-skeleton-loader
                  type="image"
                  width="180"
                  height="180"
                ></v-skeleton-loader>
                <div class="flex-grow-1">
                  <v-skeleton-loader
                    type="text,text,text"
                    class="mb-4"
                  ></v-skeleton-loader>
                </div>
                <div class="text-right">
                  <v-skeleton-loader type="text" width="80"></v-skeleton-loader>
                </div>
              </div>
            </v-col>
          </v-row>
        </v-card>

        <!-- Main Content -->
        <v-card v-else elevation="0" rounded="lg" class="px-6 py-4 w-full">
          <!-- Status Header -->
          <v-row align="center" justify="space-between" class="mb-4">
            <v-col cols="auto">
              <span class="text-h6">有效期: {{ info?.lifespan || 0 }}日</span>
            </v-col>
            <v-col cols="auto" class="d-flex gap-2">
              <v-chip :color="downloadStatusColor" class="font-weight-medium">
                {{ downloadStatusText }}
              </v-chip>
              <v-chip v-if="info.fileType" :color="fileTypeColor" class="font-weight-medium">
                {{ info.fileType }}
              </v-chip>
            </v-col>
          </v-row>

          <!-- Product Info -->
          <v-row v-if="info.id">
            <v-col cols="12">
              <div class="d-flex gap-4">
                <v-img
                  :src="getFullPath(info.productImageUrl)"
                  width="180"
                  height="180"
                  cover
                  class="rounded"
                  :lazy-src="'/placeholder.jpg'"
                >
                  <template v-slot:placeholder>
                    <v-row class="fill-height ma-0" align="center" justify="center">
                      <v-progress-circular indeterminate color="black"></v-progress-circular>
                    </v-row>
                  </template>
                </v-img>
                <div class="flex-grow-1">
                  <h1 class="text-h6 mb-2">{{ info.name }}</h1>
                  <div class="d-flex flex-wrap gap-4 text-body-2 text-medium-emphasis">
                    <span>ID: {{ info.id }}</span>
                    <span>类型: {{ info.fileType }}</span>
                    <span>大小: {{ formatFileSize(info.fileSize) }}</span>
                  </div>
                  <!-- <v-btn
                    v-if="info.id"
                    color="black"
                    variant="text"
                    class="mt-4"
                    @click="handlePreview"
                    prepend-icon="mdi-eye"
                  >
                    预览素材
                  </v-btn> -->
                </div>
                <div class="text-right">
                  <span class="text-h5 font-weight-bold">{{ formattedPrice }}</span>
                  <span class="text-body-2">{{formattedPrice=="免费"?'':'元'}}</span>
                </div>
              </div>
            </v-col>
          </v-row>

          <!-- Error State -->
          <v-row v-else-if="loadError">
            <v-col cols="12">
              <v-alert color="error" variant="tonal" border="start">
                <template v-slot:prepend>
                  <v-icon>mdi-alert-circle</v-icon>
                </template>
                <div class="d-flex flex-column gap-2">
                  <div>产品信息加载失败</div>
                  <v-btn
                    color="error"
                    variant="text"
                    size="small"
                    @click="initializeComponent"
                    :loading="isLoading"
                  >
                    <v-icon start>mdi-refresh</v-icon>
                    重新加载
                  </v-btn>
                </div>
              </v-alert>
            </v-col>
          </v-row>

          <!-- Payment Section -->
          <v-row v-if="!paySuccess && info.id" class="mt-6" justify="center">
            <v-col cols="12" md="12" class="text-center">
              <v-btn
                block
                color="black"
                size="large"
                @click="doPay"
                :loading="isProcessingOrder"
              >
                <v-icon start>mdi-wechat</v-icon>
                {{goPayment?"继续支付":"立即购买"}}
              </v-btn>
            </v-col>
          </v-row>

          <!-- Payment Dialog -->
          <v-dialog v-model="showPaymentDialog" max-width="400" persistent>
            <v-card class="pa-4">
              <v-card-title class="text-center text-h6 pb-4">
                微信扫码支付
                <v-btn
                  icon="mdi-close"
                  variant="text"
                  size="small"
                  class="position-absolute"
                  style="right: 8px; top: 8px"
                  @click="toggleCancelPayment"
                ></v-btn>
              </v-card-title>

              <v-card-text class="text-center">
                <div class="text-h5 font-weight-bold mb-4">
                  {{ formattedPrice }}
                  <span class="text-body-2">元</span>
                </div>

                <v-img
                  v-if="orderInfo.qrcodeInfo"
                  :src="orderInfo.qrcodeInfo"
                  width="200"
                  height="200"
                  class="mx-auto mb-4"
                >
                  <template v-slot:placeholder>
                    <v-row class="fill-height ma-0" align="center" justify="center">
                      <v-progress-circular indeterminate color="black"></v-progress-circular>
                    </v-row>
                  </template>
                </v-img>

                <div v-if="orderInfo.wx_pay_timeout" class="mt-4">
                  <v-progress-linear
                    :model-value="timeoutProgress"
                    color="black"
                    height="8"
                    rounded
                  ></v-progress-linear>
                  <div class="mt-2 text-body-2">
                    支付倒计时: {{ countdown }}
                  </div>
                </div>

                <v-btn
                  color="error"
                  variant="text"
                  block
                  class="mt-4"
                  @click="handleCancelPayment"
                  :loading="isProcessingOrder"
                >
                  取消支付
                </v-btn>
              </v-card-text>
            </v-card>
          </v-dialog>

          <!-- Post Payment Success -->
          <v-row v-if="paySuccess" class="mt-6">
            <v-col cols="12">
              <v-alert color="success" variant="tonal" border="start" class="mb-4">
                <template v-slot:prepend>
                  <v-icon>mdi-check-circle</v-icon>
                </template>
                <div class="font-weight-medium">支付成功</div>
                <div class="text-body-2 mt-1">
                  您已获得{{ info.lifespan }}天的下载权限
                </div>
              </v-alert>

              <v-dialog v-model="showDownloadDialog" max-width="500">
                <v-card>
                  <v-card-title class="text-h6 pa-4 flex align-center">
                    下载链接
                    <v-spacer></v-spacer>
                    <v-btn icon="mdi-close" variant="text" @click="showDownloadDialog = false"></v-btn>
                  </v-card-title>
                  <v-card-text class="pa-4">
                    <v-alert color="black" variant="tonal" class="mb-4">
                      <p class="mb-2">请在有效期内完成下载，链接将在{{ info.lifespan }}天后失效</p>
                      <v-text-field
                        v-model="downloadUrl"
                        readonly
                        variant="outlined"
                        dense
                        append-inner-icon="mdi-content-copy"
                        @click:append-inner="copyDownloadUrl"
                      ></v-text-field>
                    </v-alert>
                  </v-card-text>
                </v-card>
              </v-dialog>

              <v-row justify="center" class="mt-4">
                <v-col cols="12" md="12">
                  <v-btn
                    block
                    color="black"
                    size="large"
                    :loading="isDownloading"
                    :disabled="!info.id"
                    @click="handleDownload"
                  >
                    <v-icon start>mdi-download</v-icon>
                    {{ isDownloading ? "正在获取下载链接..." : "立即下载" }}
                  </v-btn>
                </v-col>
              </v-row>

              <v-row class="mt-6">
                <v-col cols="12">
                  <div class="text-body-2 text-medium-emphasis">
                    <div class="mb-2 d-flex align-center gap-2">
                      <v-icon size="small">mdi-clock-outline</v-icon>
                      下载链接有效期{{ info.lifespan }}天
                    </div>
                    <div class="d-flex align-center gap-2">
                      <v-icon size="small">mdi-shield-check-outline</v-icon>
                      正版授权，可商用
                    </div>
                  </div>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { orderCreate, orderCancelPay, getOrderPayInfo } from "@/api/order";
import qrcode from "qrcode";
import dayjs from "dayjs";
import { getFullPath } from "@/utils/tools";
import { getMaterialDetail } from "@/api/material";
import { orderDownload,orderDetail } from "@/api/order";
import { isNumber } from "lodash-es";

const route = useRoute();
const info = ref({});
const orderInfo = ref({});
const paymentCheckInterval = ref(null);
const countdownInterval = ref(null);
const downloadProgressInterval = ref(null);
const countdown = ref("");
const paySuccess = ref(false);
const isDownloading = ref(false);
const isProcessingOrder = ref(false);
const showDownloadDialog = ref(false);
const showPaymentDialog = ref(false);
const downloadUrl = ref("");
const initialTimeout = ref(null);
const isLoading = ref(true);
const loadError = ref(false);
const goPayment = ref(false);
const doPay=()=>{
   if(goPayment.value){
     handleOrderActionBy();
   }else{
     handleOrderAction();
   }
}
// Computed properties
const timeoutProgress = computed(() => {
  if (!orderInfo.value.wx_pay_timeout || !initialTimeout.value) return 0;
  const total = dayjs(initialTimeout.value).diff(dayjs(), 'second');
  const current = dayjs(orderInfo.value.wx_pay_timeout).diff(dayjs(), 'second');
  return (current / total) * 100;
});

const fileTypeColor = computed(() => {
  const type = info.value?.fileType?.toLowerCase();
  if (!type) return 'grey';

  const colorMap = {
    'mp4': 'purple',
    'mov': 'deep-purple',
    'avi': 'indigo',
    'jpg': 'blue',
    'png': 'light-blue',
    'gif': 'cyan'
  };

  return colorMap[type] || 'grey';
});

const formattedPrice = computed(() => {
  console.log(info.value?.price);

  return  info.value?.price!='0'? Number(info.value?.price).toFixed(2):"免费";
});

const downloadStatusColor = computed(() => {
  if (paySuccess.value) return "success";
  if (orderInfo.value.order_number) return "warning";
  return "grey";
});

const downloadStatusText = computed(() => {
  if (paySuccess.value) return "已付款";
  if (orderInfo.value.order_number) return "待支付";
  return "未购买";
});

// Helper functions
const formatFileSize = (size) => {
  if (!size) return "0 KB";
  const units = ["B", "KB", "MB", "GB"];
  let index = 0;
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024;
    index++;
  }
  return `${size.toFixed(1)} ${units[index]}`;
};

const formatTimeout = computed(() => {
  return (endTime) => {
    if (!endTime) return "00:00:00";

    const now = dayjs();
    const end = dayjs(endTime);
    const diff = end.diff(now, "second");

    if (diff <= 0) {
      clearOrderState();
      return "00:00:00";
    }

    const hours = Math.floor(diff / 3600);
    const minutes = Math.floor((diff % 3600) / 60);
    const seconds = diff % 60;

    return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
      2,
      "0"
    )}:${String(seconds).padStart(2, "0")}`;
  };
});

const copyDownloadUrl = async () => {
  try {
    await navigator.clipboard.writeText(downloadUrl.value);
    window.$snackbar({
      showCloseButton: false,
      text: "下载链接已复制到剪贴板",
      snackbarProps: { color: "success", location: "top", timeout: 2000 },
    });
  } catch (error) {
    console.error("复制失败:", error);
    window.$snackbar({
      showCloseButton: false,
      text: "复制失败，请手动复制",
      snackbarProps: { color: "error", location: "top" },
    });
  }
};

const clearIntervals = () => {
  [paymentCheckInterval, countdownInterval, downloadProgressInterval].forEach(interval => {
    if (interval.value) {
      clearInterval(interval.value);
      interval.value = null;
    }
  });
};

const clearOrderState = () => {
  clearIntervals();
  // orderInfo.value = {};

  initialTimeout.value = null;
};

const handleOrderAction = async () => {
  if (isProcessingOrder.value) return;
  isProcessingOrder.value = true;

  try {
    const { data } = await orderCreate({
      material_id: info.value.id,
      payment_type: "1",
    });



    if(data.price=="0.00"){
      orderInfo.value = { order_number: data.order_number };
      paySuccess.value = true;
      return;
    }

    // if (data.is_paying_order) {
    //   window.$snackbar({
    //     showCloseButton: false,
    //     text: "订单已支付，请勿重复支付",
    //     snackbarProps: { color: "info", location: "top" },
    //   });
    //   paySuccess.value = true;
    //   return;
    // }

    const qrcodeInfo = await qrcode.toDataURL(data.wx_pay_url, {
      width: 500,
    });

    orderInfo.value = {
      order_number: data.order_number,
      wx_pay_timeout: data.wx_pay_timeout,
      qrcodeInfo: qrcodeInfo,
      wx_pay_url: data.wx_pay_url,
    };
    initialTimeout.value = data.wx_pay_timeout;

    showPaymentDialog.value = true;
    await checkOrderStatus();

    countdown.value = formatTimeout.value(data.wx_pay_timeout);
    countdownInterval.value = setInterval(() => {
      countdown.value = formatTimeout.value(data.wx_pay_timeout);
    }, 1000);

    paymentCheckInterval.value = setInterval(checkOrderStatus, 1000);
  } catch (error) {
    console.error("支付创建失败:", error);
    clearOrderState();
    window.$snackbar({
      showCloseButton: false,
      text: error.message || "创建支付失败，请重试",
      snackbarProps: { color: "error", location: "top" },
    });
  } finally {
    isProcessingOrder.value = false;
  }
};
const handleOrderActionBy=async ()=>{
  if (isProcessingOrder.value) return;
  isProcessingOrder.value = true;
  try {


    // if(data.price=="0.00"){
    //   orderInfo.value = { order_number: order_number };
    //   paySuccess.value = true;
    //   return;
    // }

    // if (data.is_paying_order) {
    //   window.$snackbar({
    //     showCloseButton: false,
    //     text: "订单已支付，请勿重复支付",
    //     snackbarProps: { color: "info", location: "top" },
    //   });
    //   paySuccess.value = true;
    //   return;
    // }

    const qrcodeInfo = await qrcode.toDataURL(orderInfo.value.wx_pay_url, {
      width: 500,
    });
    orderInfo.value.qrcodeInfo=qrcodeInfo;
    initialTimeout.value = orderInfo.value.wx_pay_timeout;

    showPaymentDialog.value = true;
    await checkOrderStatus();

    countdown.value = formatTimeout.value(orderInfo.value.wx_pay_timeout);
    countdownInterval.value = setInterval(() => {
      countdown.value = formatTimeout.value(orderInfo.value.wx_pay_timeout);
    }, 1000);

    paymentCheckInterval.value = setInterval(checkOrderStatus, 1000);
  } catch (error) {
    console.error("支付创建失败:", error);
    clearOrderState();
    window.$snackbar({
      showCloseButton: false,
      text: error.message || "创建支付失败，请重试",
      snackbarProps: { color: "error", location: "top" },
    });
  } finally {
    isProcessingOrder.value = false;
  }
}

const toggleCancelPayment=()=>{
  if (isProcessingOrder.value) return;
  isProcessingOrder.value = true;
  showPaymentDialog.value = false;
  isProcessingOrder.value = false;
  goPayment.value=true;
  clearOrderState();}

const handleCancelPayment = async () => {
  if (isProcessingOrder.value) return;
  isProcessingOrder.value = true;

  try {
    if (orderInfo.value?.order_number) {
      await orderCancelPay({ order_number: orderInfo.value.order_number });
    }
    clearOrderState();
    showPaymentDialog.value = false;
    goPayment.value=false;
    window.$snackbar({
      showCloseButton: false,
      text: "订单已取消",
      snackbarProps: { color: "info", location: "top" },
    });
  } catch (error) {
    console.error("取消支付失败:", error);
    window.$snackbar({
      showCloseButton: false,
      text: "取消支付失败，请重试",
      snackbarProps: { color: "error", location: "top" },
    });
  } finally {
    isProcessingOrder.value = false;
  }
};

const checkOrderStatus = async () => {
  if (!orderInfo.value?.order_number) return;

  try {
    const { data } = await getOrderPayInfo({
      order_number: orderInfo.value.order_number,
    });
    if (data.trade_state === "SUCCESS") {
      clearOrderState();
      showPaymentDialog.value = false;
      window.$snackbar({
        showCloseButton: false,
        text: "支付成功，正在准备下载界面",
        timeout: 1000,
        snackbarProps: { color: "success", location: "top", timeout: 3000 },
      });
      paySuccess.value = true;
    }
  } catch (error) {
    console.error("获取订单状态失败:", error);
  }
};

const handleDownload = async () => {
  if (isDownloading.value || !info.value?.id) return;
  isDownloading.value = true;
  console.log(orderInfo.value.order_number);

  try {
    const { data } = await orderDownload(orderInfo.value.order_number);
    if (!data?.download_url) {
      throw new Error("获取下载链接失败");
    }

    downloadUrl.value = data.download_url;
    showDownloadDialog.value = true;
  } catch (error) {
    console.error("下载失败:", error);
    window.$snackbar({
      showCloseButton: false,
      text: error.message || "获取下载链接失败，请重试",
      snackbarProps: { color: "error", location: "top" },
    });
  } finally {
    isDownloading.value = false;
  }
};

const handlePreview = () => {
  if (!info.value?.id) return;
  window.open(`https://www.vjshi.com/watch/${info.value.id}.html?preview=1`);
};

const initializeComponent = async () => {
  const { id, categoryId, orderNumber } = route.query;
  isLoading.value = true;
  loadError.value = false;

  if (!id) {
    isLoading.value = false;
    loadError.value = true;
    window.$snackbar({
      showCloseButton: false,
      text: "产品信息无效",
      snackbarProps: { color: "error", location: "top" },
    });
    return;
  }

  try {
    const { data } = await getMaterialDetail({ id });
    console.log(+data.price.price==0?"免费":data.price.price);

    info.value = {
      id: data.id,
      categoryId: data.category_id,
      name: data.name,
      fileType: data.file_type,
      price:  +data.price.price,
      productImageUrl: data.material_files.find(item => item.static == '1')?.file_path || '',
      fileSize: data.file_size || 1024 * 1024 * 10,
      lifespan: data.price.lifespan || 7,
    };

    if (orderNumber ) {
      orderInfo.value = { order_number: orderNumber };
      const { data: orderData } = await orderDetail({ order_number: orderNumber });
      console.log(orderData);
      if (orderData.trade_state === "SUCCESS") {
        paySuccess.value = true;
      }else if(orderData.trade_state === "NOTPAY"){
        goPayment.value=true;
        orderInfo.value.wx_pay_timeout=orderData.wx_pay_timeout;
        orderInfo.value.wx_pay_url=orderData.wx_pay_url;
        // 处理未支付订单
      }
    }
  } catch (error) {
    console.error("获取产品信息失败:", error);
    loadError.value = true;
    orderInfo.value = {};
    // window.$snackbar({
    //   showCloseButton: false,
    //   text: "获取产品信息失败",
    //   snackbarProps: { color: "error", location: "top" },
    // });
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  initializeComponent();
});

onUnmounted(() => {
  clearIntervals();
});
</script>

<style scoped>
.v-card {
  background-color: white;
  border: 1px solid rgba(0, 0, 0, 0.12);
}

.v-progress-linear {
  border-radius: 4px;
}

.preview-button {
  opacity: 0.8;
  transition: opacity 0.2s;
}

.preview-button:hover {
  opacity: 1;
}

.position-absolute {
  position: absolute;
}
</style>
